package com.hmjk.health.health;

import java.util.ArrayList;
import java.util.Calendar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.ViewSwitcher;
import android.widget.ImageView.ScaleType;

import com.hmjk.health.HealthApp;
import com.hmjk.health.FocusFragment;
import com.hmjk.health.R;
import com.hmjk.health.background.DataManager;
import com.hmjk.health.home.BaseHomeActions;
import com.hmjk.health.home.HomeActivity;
import com.hmjk.health.setting.SettingsConstants;
import com.hmjk.health.util.BP_Evaluator;
import com.hmjk.health.util.BP_Evaluator.Result;
import com.hmjk.health.util.BloodPressureData;
import com.hmjk.health.util.BloodPressureData.BP_DETAIL;
import com.hmjk.health.util.DEV_DATA;
import com.hmjk.health.util.HEALTH_KEY;
import com.hmjk.health.util.GlycoseData;
import com.hmjk.health.util.GlycoseReferenceSet;
import com.hmjk.health.util.MULTI_USER_DEV_DATA;
import com.hmjk.health.util.GlycoseData.GLY_DETAIL;
import com.hmjk.health.views.HorizontalPillarView;
import com.hmjk.health.views.PagerIndexStrip;
import com.hmjk.health.views.RoundImageView;

public class HealthHomeFragment extends FocusFragment implements OnClickListener{
	private final String TAG = HealthHomeFragment.class.getSimpleName();
	private HealthApp mApp = null;
	private ImageView scanView;
	private LinearLayout mUserView;
	private RelativeLayout mSignView;
	private boolean attached = false;
	
	/*AD*/
	private ViewSwitcher mADSwitcher = null;
	private PagerIndexStrip mADIndexView = null;
	private int mADIndex = 0;
	private float ad_downx;
	//private Animation left2right_in;
	private Animation right2left_out;
	//private Animation left2right_out;
	private Animation right2left_in;
	private int mADCount = 0;
	
	/*user view*/
	private RoundImageView mPhoto;
	private TextView mName;
	private TextView mAdvise;
	private HorizontalPillarView mPillar;
	private TextView mBPHigh;
	private TextView mBPLow;
	private ImageButton refreshBut;
	private Animation cycleAnim;
	private boolean glyRefreshing = false;
	private boolean blpRefreshing = false;
	
	/*data*/
	private MULTI_USER_DEV_DATA mHealthMajor = null;
	private GlycoseReferenceSet mGlyRefSet = null;
	private GlycoseData mGlyData = null;
	private BloodPressureData mBpData = null;
	private boolean shouldCheckGlyData = false;
	private float minNormal = 4.4f,maxNormal = 8.0f, minGlu = 0.8f, maxGlu = 11.6f;
	
	private BP_DETAIL mLastBpDetail = null;
	private GlucLevel mGlucLevel = null;
	
	class GlucLevel{
		int glucHighs = 0;
		int glucLows = 0;
		float glucAverageValue = 0.0f;
		public void clear(){
			glucHighs = 0;
			glucLows = 0;
			glucAverageValue = 0.0f;
		}
		//float glucHighestValue = 0;
		//float glucLowestValue = 0;
	}
	
	private void logd(String info){
		Log.d(TAG,info);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
		logd("onCreateView");
		mApp = (HealthApp)getActivity().getApplication();
		mADCount = mApp.getADnumber();
		mADIndex = 0;
		
		View v = inflater.inflate(R.layout.health_home, container, false);
		
		scanView = (ImageView) v.findViewById(R.id.scan);
		scanView.setOnClickListener(this);
		
		ImageView index = (ImageView) v.findViewById(R.id.toindex);
		index.setOnClickListener(this);
		
		refreshBut = (ImageButton)v.findViewById(R.id.refreshBut);
		refreshBut.setOnClickListener(this);
		refreshBut.setEnabled(true);
		
		cycleAnim = AnimationUtils.loadAnimation(this.getActivity(), R.anim.rotatecycledfast);
		 
		mSignView = (RelativeLayout) v.findViewById(R.id.sign_layout);
		LinearLayout signFace = (LinearLayout) v.findViewById(R.id.signface);
		signFace.setOnClickListener(this);
		
		mUserView = (LinearLayout) v.findViewById(R.id.user_view);
		mPhoto = (RoundImageView) mUserView.findViewById(R.id.photo);
		mName = (TextView) mUserView.findViewById(R.id.name);
		mAdvise = (TextView)mUserView.findViewById(R.id.advise);
		
		TextView toCard = (TextView) mUserView.findViewById(R.id.to_card);
		String htmlstr = getResources().getString(R.string.enter_card);
		toCard.setText(Html.fromHtml(htmlstr));
		toCard.setOnClickListener(this);
		
		View cv = mUserView.findViewById(R.id.health_card_act_view);
		cv.setOnClickListener(this);
		
		mPillar = (HorizontalPillarView) mUserView.findViewById(R.id.glu_pillar);
		mPillar.SetParameter(minGlu, maxGlu, minNormal, maxNormal, 6.1f);
		mPillar.setTipStr("- -","");
		
		mBPHigh = (TextView) mUserView.findViewById(R.id.bp_high);
		mBPHigh.setText(getResources().getString(R.string.SBP)+" - -");
		mBPLow = (TextView) mUserView.findViewById(R.id.bp_low);
		mBPLow.setText(getResources().getString(R.string.DBP)+" - -");
		
		//left2right_in = AnimationUtils.loadAnimation(getActivity(), R.anim.l_to_r_in_s);
		right2left_out = AnimationUtils.loadAnimation(getActivity(), R.anim.r_to_l_out_s);
		right2left_in = AnimationUtils.loadAnimation(getActivity(), R.anim.r_to_l_in_s);
		//left2right_out = AnimationUtils.loadAnimation(getActivity(), R.anim.l_to_r_out_s);
		mADSwitcher = (ViewSwitcher)v.findViewById(R.id.ad_switcher);
		mADSwitcher.setOnTouchListener(new View.OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent e) {
				if(e.getAction() == MotionEvent.ACTION_DOWN){
					ad_downx = e.getX();
					mApp.ADDebug("Fragment, touch ACTION_DOWN, x=" + ad_downx);
					return true;
				}else if(e.getAction() == MotionEvent.ACTION_UP){
					float up = e.getX();
					mApp.ADDebug("Fragment, touch ACTION_UP, x=" + up);
					int count = mApp.getADnumber();
					if(count == 0){
						return true;
					}
					if(count == 1){
						//only one
						return true;
					}
					if(ad_downx - up > 100){
						/*mADIndex ++;
						mADIndex = mADIndex%count;
						mADSwitcher.setInAnimation(right2left_in);
						mADSwitcher.setOutAnimation(right2left_out);
						updateADView();*/
					}else if(up - ad_downx > 100){
						/*if(mADIndex > 0)
							mADIndex --;
						else
							mADIndex = count-1;
						mADSwitcher.setInAnimation(left2right_in);
						mADSwitcher.setOutAnimation(left2right_out);
						updateADView();*/
					}else{
						mApp.openADLink(indexToKey(mADIndex));
					}
					return true;
				}
				return false;
			}
		});
		mADIndexView = (PagerIndexStrip)v.findViewById(R.id.ad_index);
		mADIndexView.setCount(Math.max(mADCount, 1));
		if(mADCount > 1){
			mADIndexView.setVisibility(View.VISIBLE);
		}else{
			mADIndexView.setVisibility(View.INVISIBLE);
		}
		
		mADIndex = 0;
		mADSwitcher.setDisplayedChild(0);
		
		refreshDevList();
		return v;
	}
	
	private String indexToKey(int index){
		String key = SettingsConstants.KEY_AD_01;
		if(index == 1){
			key = SettingsConstants.KEY_AD_02;
		}else if(index == 2){
			key = SettingsConstants.KEY_AD_03;
		}
		return key;
	}
	
	private void getMajorAccount(){
		mHealthMajor = null;
		SharedPreferences p = mApp.getSharedPreferences(SettingsConstants.GENERAL_SETTING, Context.MODE_PRIVATE);
		String major = p.getString(SettingsConstants.KEY_HEALTH_MAJOR, "");
		if(major.trim().isEmpty()){
			mHealthMajor = null;
			return;
		}
		
		int pos = major.indexOf("-");
		if(pos <= 0){
			mHealthMajor = null;
			return;
		}
		
		String tid = major.substring(0, pos);
		String subcode = major.substring(pos+1);
		mHealthMajor = new MULTI_USER_DEV_DATA();
		mHealthMajor.id = tid;
		mHealthMajor.subcode = subcode;
	}
	
	private void refreshDevList(){
		if(mApp.isUserSignIn()){
		mApp.getDataManager().refreshData(DataManager.F_DEVICELIST);
		}
	}
	
	private boolean checkMajorAccountData(){
		boolean changed = false;
		
		if(mHealthMajor != null){
			String[] arg1 = new String[2];
			arg1[0] = "DEV_TID";
			arg1[1] = mHealthMajor.id;
			JSONObject devjson = (JSONObject) mApp.getDataManager().checkData(DataManager.F_DEVICELIST, arg1);
					
			if(devjson != null){
				try{
					JSONArray ar = devjson.getJSONArray("array");
					if(ar.length() > 0){
						JSONObject e = ar.getJSONObject(0);
						String type = e.getString("type");
						if(DEV_DATA.isHealthDev(type) == false){
							mHealthMajor = null;
						}else{
							mHealthMajor.id = e.getString("tid");
							mHealthMajor.name = e.getString("name");
								
							String ss = e.getString("status");
							mHealthMajor.status = Integer.parseInt(ss);
								
							mHealthMajor.type = type;
								
							String a = e.getString("admin");
							mHealthMajor.admin = Integer.parseInt(a);
						}
					}else{
						mHealthMajor = null;
					}
				} catch (JSONException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}else{
				mHealthMajor = null;
			}
		}

		if(mHealthMajor != null){
			String[] args = new String[3];
			args[0] = "TID_SUBCODE";
			args[1] = mHealthMajor.id;
			args[2] = mHealthMajor.subcode;
			JSONObject subinfo = (JSONObject) mApp.getDataManager().checkData(DataManager.F_DEVICESUBINFO,args);
			if(subinfo != null){
				try {
					JSONArray subar = subinfo.getJSONArray("array");
					int sublen = subar.length();
					if(sublen > 0){
						JSONObject subone = subar.getJSONObject(0);
						
						mHealthMajor.nick = subone.getString("nickname");
						mHealthMajor.birthday = subone.getString("birthday");
						mHealthMajor.gender = subone.getString("gender");
						mHealthMajor.height = subone.getDouble("height");
						mHealthMajor.weight = subone.getDouble("weight");
					}else{
						mHealthMajor = null;
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else{
				mHealthMajor = null;
			}
		}
		
		if(mHealthMajor == null){
			changed = true;
			String[] args = new String[2];
			args[0] = "FIRST";
			JSONObject subinfo = (JSONObject) mApp.getDataManager().checkData(DataManager.F_DEVICESUBINFO,args);
			if(subinfo != null){
				try{
					JSONArray subar = subinfo.getJSONArray("array");
					int sublen = subar.length();
					if(sublen > 0){
						MULTI_USER_DEV_DATA d = new MULTI_USER_DEV_DATA();
						for(int j = 0; j < sublen; j++){
							JSONObject subone = subar.getJSONObject(j);
										
							/*multi account data*/
							String scode = subone.getString("subcode");
							boolean replace = false;
							if(d.subcode == null){
								replace = true;
							}else{
								int cur = Integer.parseInt(d.subcode);
								int cmp = Integer.parseInt(scode);
								if(cmp < cur){
									replace = true;
								}
							}
							
							if(replace == false)
								continue;
							
							d.id = subone.getString("tid");
							d.subcode = scode;
							d.nick = subone.getString("nickname");
							d.birthday = subone.getString("birthday");
							d.gender = subone.getString("gender");
							d.height = subone.getDouble("height");
							d.weight = subone.getDouble("weight");
						}
						mHealthMajor = d;
					}
				} catch (JSONException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
			
			if(mHealthMajor != null){
				SharedPreferences p = mApp.getSharedPreferences(SettingsConstants.GENERAL_SETTING, Context.MODE_PRIVATE);
				SharedPreferences.Editor e = p.edit();
				String major = mHealthMajor.id + "-" + mHealthMajor.subcode;
				e.putString(SettingsConstants.KEY_HEALTH_MAJOR, major);
				e.commit();
			}else{
				SharedPreferences p = mApp.getSharedPreferences(SettingsConstants.GENERAL_SETTING, Context.MODE_PRIVATE);
				SharedPreferences.Editor e = p.edit();
				String major = "";
				e.putString(SettingsConstants.KEY_HEALTH_MAJOR, major);
				e.commit();
			}
		}
		
		return changed;
	}
	
	private long get7DaysAgo()
	{
		Calendar c = Calendar.getInstance();
		c.set(Calendar.HOUR, 0);
		c.set(Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);
		
		long ret = c.getTimeInMillis();
		ret = ret - 6*24*3600*1000;
		return ret;
	}

	private void checkData(){
		if(mHealthMajor == null)
			return;
		
		
		checkGlucoseData();
		checkBpData();
		
	}
		
	private void checkGlucoseData(){
		String[] arg = {mHealthMajor.id};		
		mGlyRefSet = (GlycoseReferenceSet) mApp.getDataManager().checkData(DataManager.F_GLYCOSE_SET, arg);
		if(mGlyRefSet != null)
		{			
			minNormal = Math.min(mGlyRefSet.beforelow, mGlyRefSet.afterlow);
			minNormal = Math.min(mGlyRefSet.bedtimelow, minNormal);
			minNormal = Math.min(mGlyRefSet.dawnlow, minNormal);
			maxNormal = Math.max(mGlyRefSet.beforeupper, mGlyRefSet.afterupper);
			maxNormal = Math.max(mGlyRefSet.bedtimeupper, maxNormal);
			maxNormal = Math.max(mGlyRefSet.dawnupper, maxNormal);
			
			float l,h;
			l = minNormal - (maxNormal - minNormal);
			if(l > 0 && l < minGlu )
				minGlu = l;
			h = maxNormal + (maxNormal - minNormal);
			
			if(h < 33 && h > maxNormal)
				maxGlu = h;				
		}
		
		String[] args = new String[4];
		args[0] = mHealthMajor.id;
		args[1] = mHealthMajor.subcode;
		long start = get7DaysAgo();
		long end = System.currentTimeMillis();
		args[2] = Long.toString(start);
		args[3] = Long.toString(end);		
		this.mGlyData = (GlycoseData) mApp.getDataManager().checkData(DataManager.F_GLYCOSE_DATA, args);
		Float glySum = 0.0f;
		ArrayList<GLY_DETAIL> list = mGlyData.getAddrList();
		int size = list.size();
		if(size >= 0){
			if(mGlucLevel == null)
				mGlucLevel = new GlucLevel();
			else{
				mGlucLevel.clear();
			}
			for(GLY_DETAIL d:list){
				if(d.bgvalue > 0.0f){
					glySum += d.bgvalue;
					//mGlucLevel.glucHighestValue = Math.max(mGlucLevel.glucHighestValue, d.bgvalue);
					//mGlucLevel.glucLowestValue = Math.min(mGlucLevel.glucLowestValue, d.bgvalue);
					if((d.bgtype == GlycoseData.TYPE_GLUC_EMPTY_STOMACH) ||
						(d.bgtype == GlycoseData.TYPE_GLUC_BEFORE_LUNCH) ||
						(d.bgtype == GlycoseData.TYPE_GLUC_BEFORE_DINNER)){
						//before
						if(d.bgvalue < mGlyRefSet.beforelow)
							mGlucLevel.glucLows++;
						else if(d.bgvalue > mGlyRefSet.beforeupper){
							mGlucLevel.glucHighs++;
						}
					}else if((d.bgtype == GlycoseData.TYPE_GLUC_AFTER_BREAKFAST) ||
							(d.bgtype == GlycoseData.TYPE_GLUC_AFTER_LUNCH) ||
							(d.bgtype == GlycoseData.TYPE_GLUC_AFTER_DINNER)){
						//after
						if(d.bgvalue < mGlyRefSet.afterlow)
							mGlucLevel.glucLows++;
						else if(d.bgvalue > mGlyRefSet.afterupper){
							mGlucLevel.glucHighs++;
						}
					}else if(d.bgtype == GlycoseData.TYPE_GLUC_AT_BEDTIME){
						if(d.bgvalue < mGlyRefSet.bedtimelow)
							mGlucLevel.glucLows++;
						else if(d.bgvalue > mGlyRefSet.bedtimeupper){
							mGlucLevel.glucHighs++;
						}
					}else if(d.bgtype == GlycoseData.TYPE_GLUC_BEFORE_DAWN){
						if(d.bgvalue < mGlyRefSet.dawnlow)
							mGlucLevel.glucLows++;
						else if(d.bgvalue > mGlyRefSet.dawnupper){
							mGlucLevel.glucHighs++;
						}
					}
				}
			}
			mGlucLevel.glucAverageValue = (float)(Math.round((glySum/size)*100))/100;
		}
		
	}
	
	private void checkBpData(){
		
		String[] args = new String[2];
		args[0] = mHealthMajor.id;
		args[1] = mHealthMajor.subcode;
		mBpData = (BloodPressureData) mApp.getDataManager().checkData(DataManager.F_BP_DATA, args);
		if(mBpData == null){
			return;
		}
		
		if(mBpData.getListSize() > 0){
			mLastBpDetail = mBpData.getDataList().get(0);
		}
		
	}
	
	private int birthday2Age(String birthday){
		int pos = birthday.indexOf("-");
		String years = birthday.substring(0, pos);
		int yeari = Integer.parseInt(years);
		Time time = new Time();
		time.setToNow();
		int age = time.year - yeari;
		return age;
	}
	
	private int getIconByAgeAndGender(int age, String gender){
		//return R.drawable.default_photo;
		if(gender.equalsIgnoreCase("F")){
			if(age == -1){
				return R.drawable.health_account_lady;
			}else if(age < 16){
				return R.drawable.health_account_girl;
			}else if(age > 60){
				return R.drawable.health_account_oldlady;
			}else {
				return R.drawable.health_account_lady;
			}
		}else {
			if(age == -1){
				return R.drawable.health_account_man;
			}else if(age < 16){
				return R.drawable.health_account_boy;
			}else if(age > 60){
				return R.drawable.health_account_oldman;
			}else {
				return R.drawable.health_account_man;
			}
		}
	}
	
	private void updateUserView(){
		if(attached == false)
			return;
		
		if(isFocused() == false)
			return;
		
		if(mUserView.getVisibility() == View.VISIBLE){
			if(mHealthMajor == null){
				mPhoto.setImageResource(R.drawable.health_account_man);
				mName.setText(R.string.no_health_account);
				mAdvise.setText(R.string.no_health_account_hint);
				
				mPillar.SetParameter(minGlu, maxGlu, minNormal, maxNormal, 6.1f);
				mPillar.setTipStr("- -","");

				
				mBPHigh.setText(getResources().getString(R.string.SBP)+" - -");
				mBPLow.setText(getResources().getString(R.string.DBP)+" - -");
			}else{
				
				if(mHealthMajor.birthday.trim().isEmpty()){
					int icon = getIconByAgeAndGender(-1,mHealthMajor.gender);
					mPhoto.setImageResource(icon);
				}else{
					int age = birthday2Age(mHealthMajor.birthday);
					int icon = getIconByAgeAndGender(age,mHealthMajor.gender);
					mPhoto.setImageResource(icon);
				}
				
				if((mHealthMajor.nick != null) && (mHealthMajor.nick.trim().length() > 0)){
					mName.setText(mHealthMajor.nick);
				}else{
					String name = getResources().getString(R.string.noName);
					if((mHealthMajor.name != null) && (mHealthMajor.name.trim().length() > 0)){
						name = mHealthMajor.name;
					}
					String subcode = String.valueOf(mHealthMajor.subcode);
					if(subcode.length() < 2){
						subcode = "0"+subcode;
					}
					mName.setText(name+" "+subcode);
				}
				
				if((mGlucLevel != null) && (mGlucLevel.glucAverageValue != 0)){
					mPillar.SetParameter(minGlu, maxGlu, minNormal, maxNormal, mGlucLevel.glucAverageValue);
					String sglucvalue = null;
					if((mGlyRefSet != null) && (mGlyRefSet.unit == 0)){// mg/dL
						int mgdl = (int) (mGlucLevel.glucAverageValue * 18);
						sglucvalue = String.valueOf(mgdl);
					}else{
						sglucvalue = String.valueOf(mGlucLevel.glucAverageValue);
					}
					
					mPillar.setTipStr(sglucvalue,"");										
				}						
				else
				{
				mPillar.SetParameter(minGlu, maxGlu, minNormal, maxNormal, 6.1f);
				mPillar.setTipStr("- -","");
				}	
				
				//BP views
				if(mLastBpDetail != null){
					mBPHigh.setText(getResources().getString(R.string.SBP) + " " + String.valueOf(mLastBpDetail.sbp));
					mBPLow.setText(getResources().getString(R.string.DBP) + " " + String.valueOf(mLastBpDetail.dbp));
				}
				
				showAdvise();
			}
		}
	}
	
	private void showAdvise(){
		String glucinfo = null;
		if((mGlucLevel == null) || (mGlucLevel.glucAverageValue == 0.0f)){
			glucinfo = getResources().getString(R.string.advise_no_glucdata);
		}else{
			if(mGlucLevel.glucAverageValue >= 16.0f){
				glucinfo = getResources().getString(R.string.advise_glu_toohigh);
			}else if(mGlucLevel.glucAverageValue >= 11.0f){
				glucinfo = getResources().getString(R.string.advise_glu_high);
			}else if(mGlucLevel.glucAverageValue <= 2.0f){
				glucinfo = getResources().getString(R.string.advise_glu_toolow);
			}else if(mGlucLevel.glucAverageValue <= 3.0f){
				glucinfo = getResources().getString(R.string.advise_glu_low);
			}else if(mGlucLevel.glucAverageValue > maxNormal){
				glucinfo = getResources().getString(R.string.advise_glu_littlehigh);
			}else if(mGlucLevel.glucAverageValue < minNormal){
				glucinfo = getResources().getString(R.string.advise_glu_littlelow);
			}else if((mGlucLevel.glucHighs > 0) || (mGlucLevel.glucLows > 0)){
				if((mGlucLevel.glucHighs == 1) && (mGlucLevel.glucLows == 1)){
					glucinfo = getResources().getString(R.string.advise_glu_onehighonelow);
				}else if((mGlucLevel.glucHighs == 1) && (mGlucLevel.glucLows == 0)){
					glucinfo = getResources().getString(R.string.advise_glu_onehigh);
				}else if((mGlucLevel.glucHighs == 0) && (mGlucLevel.glucLows == 1)){
					glucinfo = getResources().getString(R.string.advise_glu_onelow);
				}else{
					glucinfo = getResources().getString(R.string.advise_glu_nogood);
				}
			}
		}
			
		String bginfo = null;
		if(mLastBpDetail == null){
			bginfo = getResources().getString(R.string.advise_no_bpdata);
		}else{
			Result ret = BP_Evaluator.evaluateLevel(mLastBpDetail.sbp, mLastBpDetail.dbp);
			switch(ret.type){
			case BP_Evaluator.TYPE_LOW:
				bginfo = getResources().getString(R.string.advise_blp_low);
			break;
			case BP_Evaluator.TYPE_1HIGH:
				bginfo = getResources().getString(R.string.advise_blp_1high);
			break;
			case BP_Evaluator.TYPE_2HIGH:
				bginfo = getResources().getString(R.string.advise_blp_2high);
			break;
			case BP_Evaluator.TYPE_3HIGH:
				bginfo = getResources().getString(R.string.advise_blp_3high);
			break;	
			}
		}
		
		if((bginfo == null) && (glucinfo == null)){
			mAdvise.setText(R.string.advise_good);
		}else{
			String show = glucinfo;
			if(bginfo != null){
				if(show == null){
					show = bginfo;
				}else{
					show += "\n" + bginfo;
				}
			}
			mAdvise.setText(show);
		}
	}
	
	public void dataUpdate(Intent i){
		String action = i.getAction();
		if(action.equals(DataManager.DATA_UPDATE_ACTION)){
			String t = i.getStringExtra("type");
			boolean s = i.getBooleanExtra("state", false);
			logd("dataUpdate:"+t+";"+s);
			if(t.equals(DataManager.F_DEVICESUBLIST)){
				if(s){
					if(checkMajorAccountData()){
						checkData();
						updateUserView();
						this.startrefreshHealthData();
					}
				}
			}else if(t.equals(DataManager.F_DEVICESUBINFO)){
				String tid = i.getStringExtra("tid");
				String subcode = i.getStringExtra("subcode");
				if(s && (mHealthMajor != null) && tid.equals(mHealthMajor.id) && subcode.equals(mHealthMajor.subcode)){
					checkMajorAccountData();
					checkData();
					updateUserView();
					this.startrefreshHealthData();
				}
			}else if(t.equals(DataManager.F_GLYCOSE_SET)){
				String tid = i.getStringExtra("tid");
				if(s && (mHealthMajor != null) && tid.equals(mHealthMajor.id)){
					checkData();
					updateUserView();
				}
			}else if(t.equals(DataManager.F_GLYCOSE_DATA)){
				String tid = i.getStringExtra("tid");
				String subcode = i.getStringExtra("subcode");
				if((mHealthMajor != null) && tid.equals(mHealthMajor.id) && subcode.equals(mHealthMajor.subcode)){
					boolean isFinish = i.getBooleanExtra("isFinish", false);
					boolean update = i.getBooleanExtra("state", false);
					long earlisest = i.getLongExtra("earliest", 0);
					

					   if(isFinish == true)
					   {
						  glyRefreshing = false;
						   checkData();
						   updateUserView();						  
					   }
					  /* else if(earlisest <= get7DaysAgo())
					   {
						   this.shouldCheckGlyData = true;
					   }*/						   


				}
			}else if(t.equals(DataManager.F_BP_DATA)){
				String tid = i.getStringExtra("tid");
				String subcode = i.getStringExtra("subcode");
				if((mHealthMajor != null) && tid.equals(mHealthMajor.id) && subcode.equals(mHealthMajor.subcode)){
					boolean isFinish = i.getBooleanExtra("isFinish", false);
					boolean update = i.getBooleanExtra("state", false);
					long earlisest = i.getLongExtra("earliest", 0);
					
					   if(isFinish == true)
					   {
						  blpRefreshing = false;
						  checkData();
						  updateUserView();						  
					   }
					  /* else if(earlisest <= get7DaysAgo())
					   {
						   this.shouldCheckGlyData = true;
					   }*/						   
				}
			}						
		}
	}
	
	@Override
	public void onAttach(Activity a){
		logd("onAttach");
		super.onAttach(a);
		attached = true;
	}
	
	@Override
	public void onDetach(){
		logd("onDetach");
		attached = false;
		super.onDetach();
	}
	
	@Override
	public void onResume(){
		super.onResume();
		if(mApp.isUserSignIn()){
			mUserView.setVisibility(View.VISIBLE);
			mSignView.setVisibility(View.GONE);
			getMajorAccount();
			if(isFocused()){
			checkMajorAccountData();
			checkData();
			updateUserView();
			if(mHealthMajor != null)
			{
				startrefreshHealthData();
			}			
			}
		}else{
			mUserView.setVisibility(View.GONE);
			mSignView.setVisibility(View.VISIBLE);
		}
		updateADView();
	}
	
	@Override
	public void onDestroyView(){
		logd("onDestroyView");
		mHandler.removeMessages(MSG_AD_UPDATE);
		mHandler.removeMessages(MSG_CHECK_REFRESH_ANIN);
		super.onDestroyView();
	}
	
	@Override
	public void onPause(){
		super.onPause();
		//setFocused(false);
		clearADView();
	}
	
	private void clearADView(){
		View v = mADSwitcher.getCurrentView();
		ImageView adimg = (ImageView)v.findViewById(R.id.ad_image);
		adimg.setImageResource(R.drawable.ad_default);
		adimg.setScaleType(ScaleType.FIT_XY);
	}
	
	private void updateADView(){
		mApp.ADDebug("updateADView, mADIndex=" + mADIndex);
		View v = mADSwitcher.getNextView();
		ImageView adimg = (ImageView)v.findViewById(R.id.ad_image);
		TextView adtxt = (TextView)v.findViewById(R.id.ad_text);
		mApp.showAD(adimg, adtxt, indexToKey(mADIndex));
		mADIndexView.setCurrent(mADIndex);
		mADIndexView.update();
		mADSwitcher.showNext();
		if(isFocused()){
			logd("send msg");
			mHandler.removeMessages(MSG_AD_UPDATE);
			Message m = mHandler.obtainMessage(MSG_AD_UPDATE);
			mHandler.sendMessageDelayed(m, 5000);
		}
	}
	
	private void openADLink(){
		mApp.openADLink(indexToKey(mADIndex));
	}
	
	
	private final int MSG_AD_UPDATE = 200;
	private final int MSG_CHECK_REFRESH_ANIN = 201;	
	
	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			switch(msg.what){
			case MSG_AD_UPDATE:{
				mApp.ADDebug("MSG_AD_UPDATE:mApp="+mApp);
				if(isFocused()){
					int count = mApp.getADnumber();
					
					if(mADCount != count){
						mADIndex = 0;
						mADIndexView.removeAllViews();
						mADCount = count;
						mADIndexView.setCount(Math.max(mADCount, 1));
						if(mADCount > 1){
							mADIndexView.setVisibility(View.VISIBLE);
						}else{
							mADIndexView.setVisibility(View.INVISIBLE);
						}
						mADIndexView.setCurrent(mADIndex);
						mADIndexView.update();
						mADSwitcher.setDisplayedChild(0);
						updateADView();
						break;
					}
					
					if(count <= 1){
						//only one
						if(isFocused()){
							logd("send msg");
							mHandler.removeMessages(MSG_AD_UPDATE);
							Message m = mHandler.obtainMessage(MSG_AD_UPDATE);
							mHandler.sendMessageDelayed(m, 5000);
						}
						
						break;
					}
					mADIndex ++;
					mADIndex = mADIndex%count;
					mADSwitcher.setInAnimation(right2left_in);
					mADSwitcher.setOutAnimation(right2left_out);
					updateADView();
				}
			}
			break;
			case MSG_CHECK_REFRESH_ANIN:
			{
				if(!glyRefreshing && !blpRefreshing){
					refreshBut.clearAnimation();
					refreshBut.setEnabled(true);
				}else{
					Message m = mHandler.obtainMessage(MSG_CHECK_REFRESH_ANIN);
					mHandler.sendMessageDelayed(m, 500);
				}
			}
			break;
			}
		}
	};
	
	private void startrefreshHealthData()
	{
		if(mHealthMajor != null)
		{
			refreshBut.startAnimation(cycleAnim);
			refreshBut.setEnabled(false);
			this.mGlyData = null;
			this.mBpData = null;
			HEALTH_KEY key = new HEALTH_KEY(mHealthMajor.id,mHealthMajor.subcode);				
			glyRefreshing =  mApp.getDataManager().refreshData(DataManager.F_GLYCOSE_DATA,key);	
			
			blpRefreshing = mApp.getDataManager().refreshData(DataManager.F_BP_DATA,key);	
				   
			Message m = mHandler.obtainMessage(MSG_CHECK_REFRESH_ANIN);
			mHandler.sendMessageDelayed(m, 2000);			   	 
		}
	}
	
	@Override
	public void setFocused(boolean set){
		logd("setFocused "+set);
		if(set){
			mHandler.removeMessages(MSG_AD_UPDATE);
			Message m = mHandler.obtainMessage(MSG_AD_UPDATE);
			mHandler.sendMessageDelayed(m, 5000);
		}else{
			mHandler.removeMessages(MSG_AD_UPDATE);
		}
		super.setFocused(set);
		if(set){
			if((mApp != null) && mApp.isUserSignIn()){
				checkMajorAccountData();
				checkData();
				updateUserView();
				if(mHealthMajor != null)
				{
					startrefreshHealthData();
				}
			}
		}
	}
	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.toindex:{
			((BaseHomeActions)getActivity()).quitToIndexActivity();
		}break;
		case R.id.scan:{
			((BaseHomeActions)getActivity()).openPopMenu("home",scanView);
		}break;
		case R.id.signface:{
			((BaseHomeActions)getActivity()).enterSignIn();
		}break;
		case R.id.to_card:
		case R.id.health_card_act_view:{
			if(mHealthMajor != null){
				((HomeActivity)getActivity()).openHealthCardsActivity(mHealthMajor.id,mHealthMajor.subcode);
			}else{
				((HomeActivity)getActivity()).openHealthCardsActivity(null,null);
			}
		}break;
		case R.id.refreshBut:
		{
			startrefreshHealthData();
		}
		break;
		
		}
	}
}
